package com.example.musicplayer.commonUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.palette.graphics.Palette;

import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;

public class DrawUtil {
    public static final int DARK_MUTED = 1;
    public static final int DARK_VIBRANT = 2;
    public static final int MUTED = 3;
    public static final int VIBRANT = 4;
    public static final int LIGHT_MUTED = 5;
    public static final int LIGHT_VIBRANT = 6;
    private static final int NUM_OF_DEFAULT_BITMAP = 5;
    private static int[] sDefaultBitmapId;
    private static Bitmap sDefaultMusicMenuBitmap;

    static {
        sDefaultBitmapId = new int[NUM_OF_DEFAULT_BITMAP];
        sDefaultBitmapId[0] = R.mipmap.default1;
        sDefaultBitmapId[1] = R.mipmap.default2;
        sDefaultBitmapId[2] = R.mipmap.default3;
        sDefaultBitmapId[3] = R.mipmap.default4;
        sDefaultBitmapId[4] = R.mipmap.default5;
        sDefaultMusicMenuBitmap = BitmapFactory.decodeResource(MusicPlayerApplication.getInstance().getResources(),
                R.mipmap.music_menu_default);
    }

    //返回适合放在此图片上的，主体文字的颜色值
    public static int getBodyTextColorOfPicture(Bitmap bitmap) {
        Palette.Swatch swatch = getSwatch(bitmap);
        if (swatch == null)
            return getColorNoSwatch(true);
        return swatch.getBodyTextColor();
    }

    //返回适合放在此图片上的，主体文字的颜色值
    public static int getBodyTextColorOfPicture(Bitmap bitmap, int type) {
        Palette.Swatch swatch = getSwatch(bitmap, type);
        if (swatch == null)
            return getColorNoSwatch(true);
        return swatch.getBodyTextColor();
    }

    //返回适合放在此图片上的，标题文字的颜色值
    public static int getTitleTextColorOfPicture(Bitmap bitmap) {
        Palette.Swatch swatch = getSwatch(bitmap);
        if (swatch == null)
            return getColorNoSwatch(true);
        return swatch.getTitleTextColor();
    }

    //返回适合放在此图片上的，标题文字的颜色值
    public static int getTitleTextColorOfPicture(Bitmap bitmap, int type) {
        Palette.Swatch swatch = getSwatch(bitmap, type);
        if (swatch == null)
            return getColorNoSwatch(true);
        return swatch.getTitleTextColor();
    }

    //提取图片的主要颜色
    public static int getMainColorOfPicture(Bitmap bitmap) {
        Palette.Swatch swatch = getSwatch(bitmap);
        if (swatch == null)
            return getColorNoSwatch(false);
        return swatch.getRgb();
    }

    //提取图片颜色：有活力的，暗色
    public static int getMainColorOfPicture(Bitmap bitmap, int type) {
        Palette.Swatch swatch = getSwatch(bitmap, type);
        if (swatch == null)
            return getColorNoSwatch(false);
        return swatch.getRgb();
    }

    //返回给定图片的色样
    private static Palette.Swatch getSwatch(Bitmap bitmap) {
        //获取图片调色板的色样,柔和的暗色
        Palette.Swatch swatch = null;
        swatch = getSwatch(bitmap, DARK_MUTED);
        if (swatch == null) {
            //有活力的，暗色
            swatch = getSwatch(bitmap, DARK_VIBRANT);
        }
        if (swatch == null) {
            //柔和的
            swatch = getSwatch(bitmap, MUTED);
        }
        if (swatch == null) {
            //有活力的
            swatch = getSwatch(bitmap, VIBRANT);
        }
        if (swatch == null) {
            //柔和的，亮色
            swatch = getSwatch(bitmap, LIGHT_MUTED);
        }
        if (swatch == null) {
            //有活力的，亮色
            swatch = getSwatch(bitmap, LIGHT_VIBRANT);
        }
        return swatch;
    }

    //获取指定类型的色样
    private static Palette.Swatch getSwatch(Bitmap bitmap, int swatchType) {
        //获取图片调色板对象
        Palette palette = Palette.from(bitmap).generate();
        switch (swatchType) {
            case DARK_VIBRANT:
                return palette.getDarkVibrantSwatch();
            case MUTED:
                return palette.getMutedSwatch();
            case VIBRANT:
                return palette.getVibrantSwatch();
            case LIGHT_MUTED:
                return palette.getLightMutedSwatch();
            case LIGHT_VIBRANT:
                return palette.getLightVibrantSwatch();
            case DARK_MUTED:
            default:
                return palette.getDarkMutedSwatch();
        }
    }

    //在获取色样为空时，调用此方法返回颜色值
    private static int getColorNoSwatch(boolean isOnPicture) {
        //如果要得到适合放在图片上的文本的颜色，取反差色
        if (isOnPicture)
            return Color.BLACK;
        return Color.rgb(128, 128, 128);
    }

    //处理图像高斯模糊
    public static Bitmap blurBitmap(Context context, Bitmap bitmap, float radius) {
        if (bitmap == null)
            return null;
        //创建RenderScript对象，用来处理高斯模糊
        RenderScript renderScript = RenderScript.create(context);
        //创建Allocation对象作为输入输出
        final Allocation input = Allocation.createFromBitmap(renderScript, bitmap);
        final Allocation output = Allocation.createTyped(renderScript, input.getType());
        //用来处理高斯模糊
        ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        //填充数据到Allocation
        scriptIntrinsicBlur.setInput(input);
        //设置模糊半径，其值为0-25
        scriptIntrinsicBlur.setRadius(radius);
        //启动内核，调用方法处理模糊
        scriptIntrinsicBlur.forEach(output);
        //从Allocation拷贝数据
        output.copyTo(bitmap);
        //销毁RenderScript对象
        renderScript.destroy();
        return bitmap;
    }

    //返回与屏幕长宽比例相同的bitmap
    public static Bitmap getMatchScreenBitmap(Activity activity, Bitmap bitmap) {
        int[] screenSize = DisplayUtil.getScreenSize(activity);
        if (screenSize[0] <= 0 || screenSize[1] <= 0)
            return bitmap;
        float ratio = (float) screenSize[0] / (float) screenSize[1];
        return getStableRatioBitmap(bitmap, ratio);
    }

    //返回固定宽长比的图片
    public static Bitmap getStableRatioBitmap(Bitmap bitmap, float ratio) {
        if (bitmap == null || ratio <= 0)
            return bitmap;
        float targetHeight = 1;
        float width = bitmap.getWidth();
        float height = bitmap.getHeight();
        float ratioWidth = ratio / width;
        float ratioHeight = targetHeight / height;
        int theWidth, theHeight, xTopLeft, yTopLeft;
        if (ratioWidth >= ratioHeight) {
            theWidth = (int) width;
            theHeight = (int) (1 / ratio * width);
            xTopLeft = 0;
            yTopLeft = ((int) height - theHeight) / 2;
        } else {
            theWidth = (int) (ratio * height);
            theHeight = (int) height;
            yTopLeft = 0;
            xTopLeft = ((int) width - theWidth) / 2;
        }
        try {
            bitmap = Bitmap.createBitmap(bitmap, xTopLeft, yTopLeft, theWidth, theHeight);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    //随机返回一张图片
    public static Bitmap getDefaultBitmap() {
        int index = StringUtil.getRandom(0, NUM_OF_DEFAULT_BITMAP - 1);
        return BitmapFactory.decodeResource(MusicPlayerApplication.getInstance().getResources(), sDefaultBitmapId[index]);
    }

    //返回专辑封面的默认图片
    public static Bitmap getDefaultMusicMenuBitmap() {
        return sDefaultMusicMenuBitmap;
    }

    //拷贝bitmap
    public static Bitmap copyBitmap(Bitmap bitmap) {
        if (bitmap != null)
            return bitmap.copy(bitmap.getConfig(), true);
        return null;
    }

    //得到颜色纯色图
    public static Bitmap getColorBitmap(int color) {
        Bitmap bitmap = copyBitmap(sDefaultMusicMenuBitmap);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(color);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //画倾斜的渐变色
    public static Bitmap getSlantedGradientBitmap(Bitmap bitmap, int startColor, int endColor) {
        if (bitmap == null)
            return null;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        LinearGradient linearGradient;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            long color1 = getColor(startColor);
            long color2 = getColor(endColor);
            linearGradient = new LinearGradient(0, 0, width, height, new long[]{color1, color2},
                    new float[]{0, 1}, LinearGradient.TileMode.CLAMP);
        } else {
            linearGradient = new LinearGradient(0, 0, width, height, new int[]{startColor, endColor},
                    new float[]{0, 1}, LinearGradient.TileMode.CLAMP);
        }
        Paint paint = new Paint();
        paint.setShader(linearGradient);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawRect(0, 0, width, height, paint);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取屏幕截图
    public static Bitmap getScreenShot(Activity activity) {
        if (activity == null)
            return null;
        View view = activity.getWindow().getDecorView();
        Bitmap screenShot;
        int[] screenSize = DisplayUtil.getRealScreenSize(activity);
        screenShot = Bitmap.createBitmap(screenSize[0], screenSize[1], Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(screenShot));
        return screenShot;
    }

    //color类型转换
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static long getColor(int color) {
        return Color.pack(color);
    }

    //混合两种argb颜色
    public static int mixColor(int preColor, int overlayColor) {
        int preAlpha = Color.alpha(preColor);
        int overlayAlpha = Color.alpha(overlayColor);

        int r = Color.red(preColor);
        int g = Color.green(preColor);
        int b = Color.blue(preColor);

        int overlayR = Color.red(overlayColor);
        int overlayG = Color.green(overlayColor);
        int overlayB = Color.blue(overlayColor);

        int newR = createColor(r, overlayR, preAlpha, overlayAlpha);
        int newG = createColor(g, overlayG, preAlpha, overlayAlpha);
        int newB = createColor(b, overlayB, preAlpha, overlayAlpha);

        return Color.rgb(newR, newG, newB);
    }

    //给定两种颜色分量的值和透明度，返回混合后的分量值
    private static int createColor(int pre, int overlay, int preAlpha, int overlayAlpha) {
        float a1 = (float) preAlpha / 255f;
        float a2 = (float) overlayAlpha / 255f;
        float newColor = (pre * a1 * (1 - a2) + overlay * a2) / (a1 + a2 - a1 * a2);
        return (int) newColor;
    }
}